import { createSlice } from "@reduxjs/toolkit"
import { userModel } from "../model/userMode"

export const userSlice = createSlice({
    name: 'userInfo',
    initialState: {
        list: []
    },
    reducers: {
        initList: (state, {payload}) => {
            // console.log(payload);
            return ({list:payload})
        },
        delListById:(state,{payload})=>{
            return  {
                list:state.list.filter((item:any)=>item.id!==payload)
            }
        },
        addListItem:(state,{payload}:any)=>{
            return  {
                list:state.list.concat(payload)
            }
        }
    },
})

//把数据和方法分别导出
export default userSlice.reducer;
export const { initList,delListById,addListItem} = userSlice.actions;

export  const  asyncInitList = ()=>async (dispatch:any)=>{
        let  {data:list} = await  userModel.query({});
        dispatch(initList(list));
}
export  const asyncDelListById=(payload:any)=>async (dispatch:any)=>{
    await  userModel.del(payload);
    dispatch(delListById(payload))

}
export  const asyncAddListItem=(payload:any)=>  (dispatch:any)=>new  Promise(async (resolve)=>{

    let  {data:list} = await  userModel.query({username:payload.username});
    if(list.length){
        resolve({
            code:0,
            msg:"该用户名已经存在"
        })
    }else{
        let  {data} =  await  userModel.add(payload);
        dispatch(addListItem(data));
        resolve({
            code:1,
            msg:"新增成功"
        })

    }

 })





// export const  asyncAdd = (payload:any)=>{

//     return  (dispatch:any)=>{

//         setTimeout(()=>{
//             dispatch(add(payload))
//         },3000)

//     }

// }




